<?php
/**
 * 订单类
 * @author chenlisong E-mail:chenlisong1021@163.com 
 * @version 创建时间：2016年12月6日 上午9:21:37 
 * 类说明
 */
class OrderAction extends BaseAction{
	
	public function index(){
		$Order = M('Order');$OrderDetails = M('OrderDetails');
		$param = $this->param;
		$userId = $_SESSION['HS_USER_ID'];
		$map['flag'] = 1;
		$map['user_id'] = $userId;
		if(!empty($param['status'])){
			$status = explode('_', $param['status']);
			$map['status'] = array('in',$status);
		}
		//第一次不选时间则默认取当月1号至当前时间内的订单
		if(empty($param['create_time_begin'])){
			$param['create_time_begin'] = date('Y-m-01');
		}
		if(empty($param['create_time_end'])){
			$param['create_time_end'] = date('Y-m-d');
		}
		$begin_time = strtotime($param['create_time_begin']);
		$end_time = strtotime($param['create_time_end']) + 86400 - 1;
		if(!empty($begin_time) && !empty($end_time)){
			$map['create_time'] = array(array("egt",$begin_time),array("elt",$end_time));
		}else if(!empty($begin_time)){
			$map['create_time'] = array("egt",$begin_time);
		}else if(!empty($end_time)){
			$map['create_time'] = array("elt",$end_time);
		}
		if(!empty($param['code'])){
			$map['code'] = array('like','%'.$param['code'].'%');
		}
		import('ORG.Util.Page');
		$count = $Order->where($map)->count();
		$Page = new Page($count,5);
		$show = $Page->new_show();
		$list = $Order->where($map)->order("create_time desc")->limit($Page->firstRow.','.$Page->listRows)->select();
		//组装产品
		foreach ($list as $key=>$val){
			$productList = $OrderDetails->where('flag = 1 and order_code = "'.$val['code'].'"')->field('id,photo,name,price,num,product_id')->select();
			$list[$key]['productList'] = $productList;
		}
		$this->assign('param',$param);
		$this->assign('status',$status);
		$this->assign('list',$list);
		$this->assign('page',$show);
		$this->display();
	}
	
	/**
	 * 订单详情
	 */
	public function details(){
		$Order = M('Order');$OrderDetails = M('OrderDetails');
		$param = $this->param;
		$userId = $_SESSION['HS_USER_ID'];
		$map['flag'] = 1;
		$map['code'] = $param['code'];
		$map['user_id'] = $userId;
		$data = $Order->where($map)->find();
		if(empty($data)){
			$this->error('未找到该订单！');
		}
		$where['flag'] = 1;
		$where['order_code'] = $param['code'];
		$data['detailsList'] = $OrderDetails->where($where)->select();
		$this->assign('data',$data);
		$this->display();
	}
	
	/**
	 * 准备创建订单
	 */
	public function goCreateOrder(){
		$Address = M('AddressSchool','v_');$Fields = M('Fields');$MailTime = M('MailTime');$Product = M('Product');
		$param = $this->param;
		$userId = $_SESSION['HS_USER_ID'];
		if(empty($param['ids'])){
			$this->error('请至少挑点什么吧！');
		}
		//获取地址
		$data['address'] = $Address->where('flag = 1 and user_id = '.$userId)->select();
		//获取系统字段
		$data['mailSchoolStartFee'] = (float) $Fields->where('field = "app_mail_school_start_fee" and flag = 1')->getField('value');//校园模式起送费
		$data['mailCustomFee'] = (float) $Fields->where('field = "app_mail_custom_fee" and flag = 1')->getField('value');//快递模式配送费
		$data['mailSchoolFee'] = (float) $Fields->where('field = "app_mail_school_fee" and flag = 1')->getField('value');//校园模式配送费
		$data['mailFreeFee'] = (float) $Fields->where('field = "app_mail_free_fee" and flag = 1')->getField('value');//快递模式免配送费达到金额
		//获取配送时间段,校园模式含有
		$mailTimeList = $MailTime->where('flag = 1')->field('begin_time as beginTime,end_time as endTime')->select();
		foreach($mailTimeList as $key=>$val){
			$timeStarp = strtotime(date('Y-m-d')." ".$val['beginTime']);
			if(time() < $timeStarp){
				$data['mailTimeList']['today'][] = date('m-d')." ".$val['beginTime']."-".$val['endTime'];
			}
			$data['mailTimeList']['tomorrow'][] = date("m-d",strtotime("+1 day"))." ".$val['beginTime']."-".$val['endTime'];
		}
		//获取选中的商品
		$where['flag'] = 1;
		$where['is_on'] = 1;
		$where['id'] = array('in',$param['ids']);
		$data['productList'] = $Product->where($where)->field('id,name,photo,price')->order("FIELD(id,".implode(',', $param['ids']).")")->select();
		$totalPrice = 0;
		foreach ($data['productList'] as $key=>$val){
			$data['productList'][$key]['num'] = $param['nums'][$key];
			$price = formatPrice($param['nums'][$key] * $val['price']);
			$data['productList'][$key]['totalPrice'] = $price;
			$totalPrice = $totalPrice + $price;
		}
		$data['totalPrice'] = formatPrice($totalPrice);
		$this->assign('data',$data);
		$this->display();
	}
	
	/**
	 * 创建订单
	 */
	public function createOrder(){
		$Order = M('Order');$OrderDetails = M('OrderDetails');$Address = M('AddressSchool','v_');$User = M('User');$Product = M('Product');$Fields = M('Fields');
		$param = $this->param;
		$userId = $_SESSION['HS_USER_ID'];
		$Order->startTrans();//开启事务
		//获取地址
		$addressInfo = $Address->where('id = '.$param['addressId'].' and user_id = '.$userId)->field('id,school_id,schoolName,province,city,area,address,contact_tel,contact_name')->find();
		if(empty($param['addressId']) || empty($addressInfo)){
			$this->ajaxReturn(0,"错误的地址！",0);
		}
		if(empty($param['goods'])){
			$this->ajaxReturn(0,"请至少选择一个商品！",0);
		}
		$code = '10'.date('ymdHis').rand(10, 99);
		//组装商品数据
		foreach ($param['goods'] as $k=>$v){
			$v = explode('_', $v);
			$productId = $v[0];
			$productNum = $v[1];
			$proArr[$productId] = $productNum;
			$productIds .= $productId .",";
		}
		$productIds = rtrim($productIds,",");
		$where['flag'] = 1;
		$where['id'] = array('in',$productIds);
		$productList = $Product->where($where)->field('id,photo,name,price,is_on,num')->select();
		$querySql = 'SET num = CASE id ';
		foreach ($productList as $pk=>$pv){
			$sellNum = $proArr[$pv['id']];
			if($sellNum > $pv['num']){
				$this->ajaxReturn(0,$pv['name'].'库存不足，请重新选择商品！',0);
			}
			//商品下架
			if($pv['is_on'] == 2){
				$this->ajaxReturn(0,$pv['name'].'已下架，请重新选择商品！',0);
			}
			$totalPrice += $pv['price'] * $sellNum;
			$detailsData[$pk]['order_code'] = $code;
			$detailsData[$pk]['product_id'] = $pv['id'];
			$detailsData[$pk]['photo'] = $pv['photo'];
			$detailsData[$pk]['name'] = $pv['name'];
			$detailsData[$pk]['price'] = $pv['price'];
			$detailsData[$pk]['num'] = $sellNum;
			$detailsData[$pk]['create_time'] = time();
			//组装扣除商品数量sql
			$queryIds .= $pv['id'].',';
			$querySql .= ' WHEN '.$pv['id'].' THEN num -'.$sellNum." ";
		}
		$querySql .= ' END ';
		$queryIds = substr($queryIds,0,strlen($queryIds)-1);
		$querySql .= 'where id in ('.$queryIds.')';
		//组装配送参数
		$data['province'] = $addressInfo['province'];
		$data['city'] = $addressInfo['city'];
		$data['area'] = $addressInfo['area'];
		$data['contact_name'] = $addressInfo['contact_name'];
		$data['contact_tel'] = $addressInfo['contact_tel'];
		if($addressInfo['school_id'] == 0){//快递模式
			$data['mail_type'] = 2;
			$data['address'] = $addressInfo['address'];
			$mailCustomFee = (float) $Fields->where('field = "app_mail_custom_fee" and flag = 1')->getField('value');//快递模式配送费
			$mailFreeFee = (float) $Fields->where('field = "app_mail_free_fee" and flag = 1')->getField('value');//快递模式免配送费达到金额
			if($totalPrice >= $mailFreeFee){
				$mailFee = 0;
			}else{
				$mailFee = $mailCustomFee;
			}
		}else{
			if(empty($param['mailTime'])){
				$this->ajaxReturn(0,'请选择配送时间段！',0);
			}
			$data['mail_type'] = 1;
			$data['address'] = $addressInfo['schoolName'].$addressInfo['address'];
			$mailSchoolFee = (float) $Fields->where('field = "app_mail_school_fee" and flag = 1')->getField('value');//校园模式配送费
			$mailSchoolStartFee = (float) $Fields->where('field = "app_mail_school_start_fee" and flag = 1')->getField('value');//校园模式起送费
			if($totalPrice < $mailSchoolStartFee){
				$this->ajaxReturn(0,'未达到起送金额：'.$mailSchoolStartFee.'元，再挑一点吧！',0);
			}
			$mailFee = $mailSchoolFee;
			$data['mail_time'] = $param['mailTime'];
		}
		$data['code'] = $code;
		$data['user_id'] = $userId;
		$data['register_tel'] = $User->where('id = '.$userId)->getField('tel');
		$data['total_price'] = $totalPrice;
		$data['mail_fee'] = $mailFee;
		$data['real_price'] = $totalPrice;
		$data['status'] = 1;
		$data['create_time'] = time();
		$data['remark'] = $param['remark'];
		//插入数据
		$result1 = $Order->data($data)->add();
		$result2 = $OrderDetails->addAll($detailsData);
		//扣除库存数量
		$result3 = $Product->execute('update __TABLE__ '.$querySql);
		if($result1 && $result2 && $result3){
			$Order->commit();
			$this->ajaxReturn($code,"创建成功！",1);
		}else{
			$Order->rollback();
			$this->ajaxReturn(0,'服务器繁忙！',0);
		}
	}
	
	/**
	 * 去支付
	 */
	public function payment(){
		$Order = M('Order');$User = M('User');
		$param = $this->param;
		$userId = $_SESSION['HS_USER_ID'];
		if(empty($param['orderCode'])){
			$this->error('参数错误！');
		}
		$where['flag'] = 1;
		$where['code'] = $param['orderCode'];
		$info = $Order->where($where)->find();
		if(count($info) == 0){
			$this->error('未找到该订单！');
		}
		if($info['status'] != 1){
			$this->error('订单状态错误，请重新下单！');
		}
		$balance = $User->where('id = '.$userId)->getField('balance');
		$this->assign('info',$info);
		$this->assign('balance',formatPrice($balance));
		$this->display();
	}
	
	/**
	 * 取消订单
	 */
	public function cancelOrder(){
		$Order = M('Order');
		$param = $this->param;
		$userId = $_SESSION['HS_USER_ID'];
		if(empty($param['orderCode'])){
			$this->ajaxReturn(0,'参数错误！',0);
		}
		$where['flag'] = 1;
		$where['code'] = $param['orderCode'];
		$where['user_id'] = $userId;
		$info = $Order->where($where)->find();
		if(count($info) == 0){
			$this->ajaxReturn(0,'未找到该订单！',0);
		}
		if($info['status'] != 1){
			$this->ajaxReturn(0,'错误订单状态，无法继续！');
		}
		//数量回补
		backProductNum($info['code']);
		$result = $Order->where($where)->setField(array('status'=>-1,'update_time'=>time()));
		if($result !== false){
			$this->ajaxReturn(1,'取消成功！',1);
		}else{
			$this->ajaxReturn(0,'取消失败！',0);
		}
	}
	
	/**
	 * 确认订单
	 * 上级获得分层
	 */
	public function doneOrder(){
		$Order = M('Order');$User = M('User');$Fields = M("Fields");$UserDetails = M('UserDetails');$Product = M('Product');$OrderDetails = M('OrderDetails');
		$param = $this->param;
		$userId = $_SESSION['HS_USER_ID'];
		$Order->startTrans();
		if(empty($param['orderCode'])){
			$this->ajaxReturn(0,'参数错误！',0);
		}
		$where['flag'] = 1;
		$where['code'] = $param['orderCode'];
		$where['user_id'] = $userId;
		$info = $Order->where($where)->find();
		if(count($info) == 0){
			$this->ajaxReturn(0,'未找到该订单！',0);
		}
		if(!in_array($info['status'], array(3,-3))){
			$this->ajaxReturn(0,'错误订单状态，无法继续！',0);
		}
		$parentId = $User->where('id = '.$info['user_id'])->getField('parent_id');
		$result1 = true;$result2 = true;
		//分润
		if(!empty($parentId)){
			$bl = (float) $Fields->where('field = "app_consume_return_rate" and flag = 1')->getField('value');//上级返现利率
			$price = sprintf("%.2f",$info['real_price'] * $bl);
			$parentBalance = $User->where('id ='.$parentId)->getField("balance");
			$result1 = $this->addUserDetails($parentId,"消费返利",$price,$info['user_id'],$parentBalance);
			$result2 = $User->where('id = '.$parentId)->setInc('balance',$price);
		}
		//已售数量+1
		$map['flag'] = 1;
		$map['order_code'] = $param['orderCode'];
		$udList = $OrderDetails->where($map)->field('product_id,num')->select();
		foreach ($udList as $k=>$v){
			$Product->where('id = '.$v['product_id'])->setInc('sell_num',$v['num']);
		}
		$data['status'] = 4;
		$data['done_time'] = time();
		$result3 = $Order->where($where)->save($data);
		if($result1 && $result2 && $result3){
			$Order->commit();
			$this->ajaxReturn(1,'确定成功！',1);
		}else{
			$Order->rollback();
			$this->ajaxReturn(0,'确定失败！',0);
		}
	}
	
	/**
	 * 记录金额明细
	 */
	private function addUserDetails($userId,$title,$price,$formUserId,$balance){
		$UserDetails = M('UserDetails');
		$detailData['user_id'] = $userId;
		$detailData['title'] = $title;
		$detailData['type'] = 1;
		$detailData['price'] = $price;
		$detailData['from_user_id'] = $formUserId;
		$detailData['last_price'] = $balance;
		$detailData['create_time'] = time();
		$result = $UserDetails->add($detailData);
		if($result){
			return true;
		}else{
			return false;
		}
	}
	
	/**
	 * 退款界面
	 */
	public function refund(){
		$Order = M('Order');
		$param = $this->param;
		$userId = $_SESSION['HS_USER_ID'];
		$map['flag'] = 1;
		$map['code'] = $param['orderCode'];
		$map['user_id'] = $userId;
		$data = $Order->where($map)->find();
		if(empty($data)){
			$this->error('未找到该订单！');
		}
		$this->assign('data',$data);
		$this->display();
	}
	
	/**
	 * 申请退款
	 */
	public function applyReturnOrder(){
		$Order = M('Order');
		$param = $this->param;
		if(empty($param['orderCode'])){
			$this->ajaxReturn(0,'参数错误！',0);
		}
		$where['flag'] = 1;
		$where['code'] = $param['orderCode'];
		$info = $Order->where($where)->find();
		if(count($info) == 0){
			$this->ajaxReturn(0,'未找到该订单！',0);
		}
		if(!in_array($info['status'], array(2,3))){
			$this->ajaxReturn(0,'错误订单状态，无法继续！',0);
		}
		$data['status'] = 0;
		$data['return_apply_time'] = time();
		$data['return_reason'] = $param['returnReason'].",".$param['reasonRemark'];
		$result = $Order->where($where)->save($data);
		if($result !== false){
			$this->ajaxReturn(1,"申请成功！",1);
		}else{
			$this->ajaxReturn(0,'申请失败！',0);
		}
	}
}